// JavaScript Document
_dss_editor._model.system = {};
// 四个方向，用于判断退出点所在边界的位置
_dss_editor._model.system.DIR_EAST = 0;
_dss_editor._model.system.DIR_SOUTH = 1;
_dss_editor._model.system.DIR_WEST = 2;
_dss_editor._model.system.DIR_NORTH = 3;
// 类型-----------------------------------------------------------------------------
_dss_editor._model.system._type = {};
_dss_editor._model.system._type.SYSTEM = "System";
_dss_editor._model.system._type.WORK = "Work";
_dss_editor._model.system._type.DATA = "Data";
_dss_editor._model.system._type.PROTOCOL = "Protocol";
_dss_editor._model.system._type.PREDICATE = "Predicate";
_dss_editor._model.system._type.TASK = "Task";
_dss_editor._model.system._type.NAMELABEL = 'NameLabel';
// system的最小的大小
_dss_editor._model.system.minSize = {
    width : 30,
    height : labelHeight
};

/* 如果字符太长而超过了label的长度，那么要剪裁一些字符用省略号代替 */
_dss_editor._model.system.getTrimStr = function(length, str, ctx) {
    // var ctx = _dss_editor._toolkit.getContext();
    sStr = str.split("");
    var trimStr = "";
    var ellipsis = "...";
    for (var i = 0; i < sStr.length; i++) {
        if (ctx.measureText(trimStr + ellipsis).width < length) {
            trimStr += sStr[i];
        } else {
            break;
        }
    }
    return trimStr + ellipsis;
};
_dss_editor._model.system.getSystemColor = function(system) {
    var type = system.getType();
    var color = 'black';
    if (type == this._type.SYSTEM) {
        color = 'blue';
    } else if (type == this._type.WORK) {
        color = 'green';
    } else if (type == this._type.DATA) {
        color = 'orange';
    } else if (type == this._type.PROTOCOL) {
        color = 'brown';
    } else if (type == this._type.PREDICATE) {
        color = 'purple';
    }
    return color;

};
_dss_editor._model.system.getSystemIcon = function(system) {
    var type = system.getType();
    var userType = system.userDefinedType;
    if (userType) {
        return this.getIconByUserType(userType);
    } else {
        if (type == this._type.NAMELABEL) {
            type = getValue(system.specSys.nameLabel.nameLabelType);
        }
        return this.getIconByType(type);
    }

};
_dss_editor._model.system.getIconByUserType = function(userType) {
    if (userType === 'UIW') {//这里是临时的处理，以后会读取CSS文件
        return 'icons/actor.gif';
    } else if (userType === 'SlideURL') {
        return '../themes/icons/url.png';
    } else if (userType === 'Slide') {
        return '../themes/icons/slide.png';
    }
};
_dss_editor._model.system.getIconByType = function(type) {
    if (type == this._type.SYSTEM) {
        return ICON_SYSTEM;
        // if (system.hasOwnProperty("content")) {
        // return ICON_SYSTEM;
        // } else {
        // return ICON_SYSTEM_GRAY;
        // }
    } else if (type == this._type.WORK) {
        return ICON_WORK;
        // if (system.hasOwnProperty("content")) {
        // return ICON_WORK;
        // } else {
        // return ICON_WORK_GRAY;
        // }
    } else if (type == this._type.DATA) {
        return ICON_DATA;
        // if (system.hasOwnProperty("content")) {
        // return ICON_DATA;
        // } else {
        // return ICON_DATA_GRAY;
        // }
    } else if (type == this._type.PROTOCOL) {
        return ICON_PROTOCOL;
        // if (system.hasOwnProperty("content")) {
        // return ICON_PROTOCOL;
        // } else {
        // return ICON_PROTOCOL_GRAY;
        // }
    } else if (type == this._type.PREDICATE) {
        return ICON_PREDICATE;
        // if (system.hasOwnProperty("content")) {
        // return ICON_PREDICATE;
        // } else {
        // return ICON_PREDICATE_GRAY;
        // }
    } else if (type == this._type.TASK) {
        return ICON_TASK;
        // if (system.hasOwnProperty("content")) {
        // return ICON_TASK;
        // } else {
        // return ICON_TASK_GRAY;
        // }
    }
    return null;
};
_dss_editor._model.system.createResizeHandler = function(system, bounds, canvas) {
    system.addHandle(this.createHandler(system, canvas, bounds.x, bounds.y, RESIZE_L_T, 'nw-resize'));
    system.addHandle(this.createHandler(system, canvas, bounds.x + bounds.w / 2, bounds.y, RESIZE_TOP, 'n-resize'));
    system.addHandle(this.createHandler(system, canvas, bounds.x + bounds.w, bounds.y, RESIZE_R_T, 'ne-resize'));
    system.addHandle(this.createHandler(system, canvas, bounds.x, bounds.y + bounds.h / 2, RESIZE_LEFT, 'w-resize'));
    system.addHandle(this.createHandler(system, canvas, bounds.x + bounds.w, bounds.y + bounds.h / 2, RESIZE_RIGHT, 'e-resize'));
    system.addHandle(this.createHandler(system, canvas, bounds.x, bounds.y + bounds.h, RESIZE_L_B, 'sw-resize'));
    system.addHandle(this.createHandler(system, canvas, bounds.x + bounds.w / 2, bounds.y + bounds.h, RESIZE_BOTTOM, 's-resize'));
    system.addHandle(this.createHandler(system, canvas, bounds.x + bounds.w, bounds.y + bounds.h, RESIZE_R_B, 'se-resize'));
};
_dss_editor._model.system.createHandler = function(system, canvas, x, y, mousePosition, cursor) {
    var point = {
        x : x,
        y : y
    };
    var handler = new HandleTool(system, canvas.entity, point);
    handler.onSelect = function() {
        return mousePosition;
    };
    return handler;
};
_dss_editor._model.system.createSystemSelectionHandle = function(system, canvas) {
    var bounds = _dss_editor._toolkit.translateToAbsolute(system);
    this.createResizeHandler(system, bounds, canvas);
    this.createSystemTextEditHandles(system, canvas);
    if (system.userDefinedType === 'SlideURL') {
        this.createURLHandles(system, canvas);
    }
    this.createReuseHandles(system, canvas);
};
_dss_editor._model.system.refreshSystemSelectionHandle = function(canvas) {
    for (var i in canvas.selectionDiagrams) {
        var system = canvas.selectionDiagrams[i];
        system.clearHandles();
        this.createSystemSelectionHandle(system, canvas);
    }
};
_dss_editor._model.system.createURLHandles = function(system, canvas) {
    var url = _dss_editor._urlplayer.createUrl(system.getValue());
    url = _dss_editor._toolkit.strReplaceAll(url, ' ', '%20');
    var getLocation = function() {
        var toolLoc = _dss_editor._toolkit.getToolOffsetLoc(canvas);
        var bounds = _dss_editor._toolkit.translateToAbsolute(system);
        toolLoc.x += bounds.x;
        // + _dss_editor._toolkit.getContext(canvas.entity).measureText(system.getName()).width;
        toolLoc.y += bounds.y - 20;
        return toolLoc;
    };
    var handle = function() {
        _dss_editor._urlplayer.play(url, canvas);
    };
    var urlTool = new EditTool(canvas);
    urlTool.setLocation(getLocation);
    urlTool.setHandle(handle);
    urlTool.setImgPath("themes/icons/control_play.png");
    urlTool.show();
    system.addHandle(urlTool);
    $("#div1").load(url, function(responseTxt, statusTxt, xhr) {
        if (statusTxt == "error" || url === 'file/') {            
            system.removeHandle(urlTool);
            urlTool.close();
        }
        $("#div1").html('');
    });
    

};
_dss_editor._model.system.createReuseHandles = function(system, canvas) {
    var name = system.getValue();
    var reused = _dss_editor._namespace.findSysInExNS(name, system.parent);
    var getLocation = function() {
        var toolLoc = _dss_editor._toolkit.getToolOffsetLoc(canvas);
        var bounds = _dss_editor._toolkit.translateToAbsolute(system);
        toolLoc.x += bounds.x;
        // + _dss_editor._toolkit.getContext(canvas.entity).measureText(system.getName()).width;
        toolLoc.y += bounds.y - 20;
        return toolLoc;
    };
    if (reused) {
        var reusedTool = new EditTool(canvas);
        var handle = function() {
            var newCanvas = _dss_editor._canvas._operation.buildTab(reused.name, _dss_editor._canvas._type.VIEWER);
            newCanvas.init(newCanvas.sysForView);
            var cloned = _dss_editor._toolkit.clone(reused);
            newCanvas.sysForView.complete.sys.addChild(cloned.system);
            for (var i = 0; i < cloned.links.length; i++) {
                if (cloned.links[i]) {
                    newCanvas.addLink(cloned.links[i]);
                }
            }
            newCanvas.update();
        };
        reusedTool.setLocation(getLocation);
        reusedTool.setHandle(handle);
        reusedTool.setImgPath("themes/icons/search.png");
        reusedTool.show();
        system.addHandle(reusedTool);
    } else {
        var url = 'file/' + name + '.json';
        $("#div1").load(url, function(responseTxt, statusTxt, xhr) {
            var urlTool = new EditTool(canvas);
            if (statusTxt == "success") {
                var handle = function() {
                    _dss_editor._urlplayer.playJson(name, responseTxt);
                };
                urlTool.setLocation(getLocation);
                urlTool.setHandle(handle);
                urlTool.setImgPath("themes/icons/search.png");
                urlTool.show();
                system.addHandle(urlTool);
                $("#div1").html('');
            }
        });

    }
};
_dss_editor._model.system.createSystemTextEditHandles = function(system, canvas) {
    if (system.style == SYSTEM) {
        if (system.getType() == COMMENT) {
            this.createCommentTextHandle(system, canvas);
        } else {
            if (system.getType() == this._type.PROTOCOL) {
                if (system.hasOwnProperty('content') && !system.content.hasOwnProperty('composite') && system.isShowContent()) {
                    this.createProDirTextHandle(system, canvas);
                }
            }
            if (canvas.type != _dss_editor._canvas._type.VIEWUIO) {
                if (system.hasShadow()) {
                    this.createSystemStaticCntHandle(system, canvas);
                }
                if (system.isShowLabel()) {
                    this.createSystemNameHandle(system, canvas);
                }
            }
            if (system.isShowContent() && system.getSystemComplexity() == 1) {
                this.createSystemContentHandle(system, canvas);
            }
        }
    } else if (system.type == EXITPOINT) {
        this.createExitPointTextHandle(system, canvas);
    }
};
_dss_editor._model.system.createSystemNameHandle = function(system, canvas) {
    var getLocation = function() {
        var toolLoc = _dss_editor._toolkit.getToolOffsetLoc(canvas);
        var bounds = _dss_editor._toolkit.translateToAbsolute(system);
        toolLoc.x += bounds.x + 20 + _dss_editor._toolkit.getContext(canvas.entity).measureText(system.getName()).width;
        toolLoc.y += bounds.y;
        return toolLoc;
    };
    var handle = function() {
        var input = new DscTextInput(canvas);
        input.owner = system;//@Robot 将System传递到DscTextInput里面去
        var getLoc = function() {
            var loc = getLocation();
            loc.x -= _dss_editor._toolkit.getContext(canvas.entity).measureText(system.getName()).width;
            return loc;
        };
        input.setLocation(getLoc);
        input.initText = system.getName();
        input.commiteText = function() {
            // system.setName(this.getText());
            var oldText = system.getName();
            var newText = this.getText();
            var command = new ChangeSystemNameCommand(system, newText);
            _dss_editor._command._commandsManager.doCommand(command);
        };
        input.show();
    };
    this.createTextInputHandle(handle, getLocation, system, canvas);
};
_dss_editor._model.system.createSystemContentHandle = function(system, canvas) {
    var that = this;
    var getLocation = function() {
        var toolLoc = _dss_editor._toolkit.getToolOffsetLoc(canvas);
        var bounds = _dss_editor._toolkit.translateToAbsolute(system);
        toolLoc.x += bounds.x + 12;
        toolLoc.y += bounds.y + 5;
        if (system.isShowLabel()) {
            toolLoc.y += labelHeight;
        }
        return toolLoc;
    };
    var handle = function() {
        var content = system.content.simple;
        // if (content != null && content.charAt(0) != "\"" && content.indexOf(";") > -1 && content.indexOf(",") > -1) {
        // content = content.substring(0, content.indexOf(";"));
        // var list = content.split(",");
        // for (var i in list) {
        // input.dataList.push({
        // "id" : i + 1,
        // "text" : list[i]
        // });
        // }
        // }
        // var input = new DscTextInput(canvas);
        // input.setLocation(getLocation);
        // input.initText = system.getValue();
        // input.commiteText = function() {
        // system.setValue(this.getText());
        // };
        // input.show();
        createInput(content);
    };
    var createInput = function() {
        var content = arguments[0];
        if (content.hasOwnProperty('expr')) {
            var contentType = content.expr;
            if (contentType.indexOf(';')) {
                contentType = contentType.substring(0, contentType.indexOf(";"));
            }
            if (contentType == INTEGER) {
                //数字输入
            } else if (contentType == STRING) {
                //字符串输入
            } else if (contentType == REAL) {

            } else if (contentType == CHAR) {

            } else if (contentType.indexOf(",") > -1) {
                var list = contentType.split(",");
                var dataList = [];
                for (var i in list) {
                    dataList.push({
                        id : i + 1,
                        text : list[i]
                    });
                }
                createComboInput(dataList);
            } else if (system.getType() == that._type.DATA || system.getType() == that._type.PROTOCOL) {
                var dataList = [{
                    id : 1,
                    text : CHAR
                }, {
                    id : 2,
                    text : INTEGER
                }, {
                    id : 3,
                    text : REAL
                }, {
                    id : 4,
                    text : STRING
                }];
                createComboInput(dataList);
            } else {
                createTextInput();
            }
        }
    };
    var createTextInput = function() {
        var input = new DscTextInput(canvas);
        input.owner = system;//@Robot 将System传递到DscTextInput里面去
        input.setLocation(getLocation);
        input.initText = system.getValue();
        input.commiteText = function() {
        	var newValue = this.getText();
        	var command = new ChangeSystemContentCommand(system, newValue);
        	_dss_editor._command._commandsManager.doCommand(command);
            // system.setValue(this.getText());
        };
        input.show();
    };

    var createComboInput = function() {
        var dataList = arguments[0];
        var combo = new DscComboTextInput(canvas);
        combo.setLocation(getLocation);
        combo.initText = system.getValue();
        combo.dataList = dataList;
        combo.commiteText = function() {
            system.setValue(this.getText());
        };
        combo.show();
    };

    this.createTextInputHandle(handle, getLocation, system, canvas);
};
_dss_editor._model.system.createSystemStaticCntHandle = function(system, canvas) {
    var getLocation = function() {
        var toolLoc = _dss_editor._toolkit.getToolOffsetLoc(canvas);
        var bounds = _dss_editor._toolkit.translateToAbsolute(system);
        toolLoc.x += bounds.x + bounds.w - _dss_editor._toolkit.getContext(canvas.entity).measureText(system.getStaticCnt()).width - 20;
        toolLoc.y += bounds.y;
        if (!system.isShowLabel()) {
            toolLoc.y -= labelHeight;
        }
        return toolLoc;
    };
    var handle = function() {
        var input = new DscTextInput(canvas);
        input.owner = system;//@Robot 将System传递到DscTextInput里面去
        input.setLocation(getLocation);
        input.initText = system.getStaticCnt();
        input.commiteText = function() {
            var newText = this.getText();
            var command = new ChangeSystemArrayLengthCommand(system, newText);
            _dss_editor._command._commandsManager.doCommand(command);
            // system.setStaticCnt(text);
            //ArrayTool.convertSys2Array(system, text);
            this.canvas.update();
        };
        input.show();
    };
    this.createTextInputHandle(handle, getLocation, system, canvas);
};
_dss_editor._model.system.createCommentTextHandle = function(system, canvas) {
    var getLocation = function() {
        var toolLoc = _dss_editor._toolkit.getToolOffsetLoc(canvas);
        var bounds = _dss_editor._toolkit.translateToAbsolute(system);
        toolLoc.x += bounds.x;
        toolLoc.y += bounds.y;
        return toolLoc;
    };
    var handle = function() {
        var input = new DscTextArea(canvas);
        input.setLocation(getLocation);
        input.initText = system.getValue();
        input.commiteText = function() {
        	var newText = this.getText();
        	var command = new ChangeCommentTextCommand(system, newText);
        	_dss_editor._command._commandsManager.doCommand(command);
            // system.setValue(this.getText());
        };
        input.show();
    };
    this.createTextInputHandle(handle, getLocation, system, canvas);
};
_dss_editor._model.system.createProDirTextHandle = function(system, canvas) {
    var getLocation = function() {
        var toolLoc = _dss_editor._toolkit.getToolOffsetLoc(canvas);
        var bounds = _dss_editor._toolkit.translateToAbsolute(system);
        toolLoc.x += bounds.x;
        toolLoc.y += bounds.y + bounds.h - labelHeight;
        return toolLoc;
    };
    var handle = function() {
        var input = new DscTextInput(canvas);
        input.owner = system;//@Robot 将System传递到DscTextInput里面去
        input.setLocation(getLocation);
        input.initText = system.getFrom() + PRODIR + system.getTo();
        input.commiteText = function() {
            // var dirIndex = this.getText().indexOf(PRODIR);
            // if (dirIndex != -1) {
                // var from = this.getText().substring(0, dirIndex);
                // var to = this.getText().substring(dirIndex + 1, this.getText().length);
                // system.setFrom(from);
                // system.setTo(to);
            // }
            var newText = this.getText();
            var command = new ChangeProDirTextCommand(system, newText);
            _dss_editor._command._commandsManager.doCommand(command);
        };
        input.show();
    };
    this.createTextInputHandle(handle, getLocation, system, canvas);
};
_dss_editor._model.system.createTextInputHandle = function(handle, location, system, canvas) {
    var editTextTool = new EditTool(canvas);
    editTextTool.setLocation(location);
    editTextTool.setHandle(handle);
    editTextTool.setImgPath("themes/icons/pencil.png");
    editTextTool.show();
    system.addHandle(editTextTool);
};
_dss_editor._model.system.createExitPointTextHandle = function(system, canvas) {
    var getLocation = function() {
        var loc = _dss_editor._model.link.getAnchorPoint(system.parent, system.showInfo.angle);
        var dir = _dss_editor._toolkit.calculatePointDir(loc, system.parent);
        switch(dir) {
            case this.DIR_NORTH:
                loc.y += system.getRectangle().h;
                loc.x -= 5;
                break;
            case this.DIR_SOUTH:
                loc.y -= system.getRectangle().h + 16;
                loc.x -= 5;
                break;
            case this.DIR_WEST:
                loc.x += system.getRectangle().w;
                loc.y -= 5;
                break;
            case this.DIR_EAST:
                loc.x -= system.getRectangle().w + 16;
                loc.y -= 5;
                break;
        }
        var toolLoc = _dss_editor._toolkit.getToolOffsetLoc(canvas);

        toolLoc.x += loc.x;
        toolLoc.y += loc.y;
        return toolLoc;
    };
    var handle = function() {
        var input = new DscTextInput(canvas);
        input.owner = system;//@Robot 将System传递到DscTextInput里面去
        input.setLocation(getLocation);
        input.initText = system.name;
        input.commiteText = function() {
        	var newText = this.getText();
        	var command = new ChangeExitPointTextCommand(system, newText);
        	_dss_editor._command._commandsManager.doCommand(command);
            // system.name = this.getText();
        };
        input.show();
    };
    this.createTextInputHandle(handle, getLocation, system, canvas);
};

// init
_dss_editor._model.system.initSys = function(canvas) {
    var sys = canvas.sysForView.complete.sys;
    canvas.sys = canvas.sysForView.complete.sys;
    canvas.sys.style = STYLE_ROOT;
    this.initDiagram(canvas.sys);
};
_dss_editor._model.system.initSystem = function(system) {
    system.style = SYSTEM;
    this.initDiagram(system);
};
_dss_editor._model.system.initDiagram = function(system) {
    system.handles = [];
    system.textHandles = [];
    // system的handle
    system.drillBounds = null;
    this.initSystemMethod(system);
    //if (system.getType() == this.type.PROTOCOL) {
    this.initProtocolMethod(system);
    //} else if (system.hasOwnProperty('specSys') && system.specSys.hasOwnProperty('work') && system.specSys.work.hasOwnProperty('deriveInfo') && system.specSys.work.deriveInfo.hasOwnProperty('deriveFlag')) {
    this.initWorkMethod(system);
    //}
    system.setVisible(YES);
    /*
     * 初始化会在3个地方使用，一个是打开图时，一个是创建图，还有就是复制图 打开时图的连线会在连线初始化时再联系到图元上，创建图时是没有连线的
     * 当有连线创建时会初始化连线，同样会与图元进行关联，复制图时，不复制 图元连线信息，只找到连线然后复制连线，再初始化 ，所以在这里将所有
     * 连线清空
     */
    system.transition = [];
    /* 初始化sub */
    if (system.hasOwnProperty("content") && system.content.hasOwnProperty("composite")) {
        if (system.content.composite.hasOwnProperty("subSys")) {
            for (var i = 0; i < system.content.composite.subSys.length; i++) {
                var subsys = system.content.composite.subSys[i];
                subsys.parent = system;
                this.initSystem(subsys);
            }
        }
        if (system.content.composite.hasOwnProperty("beginPoint")) {
            for (var i = 0; i < system.content.composite.beginPoint.length; i++) {
                var beginPoint = system.content.composite.beginPoint[i];
                beginPoint.parent = system;
                this.initPoint(beginPoint, BEGINPOINT);
            }
        }
        if (system.content.composite.hasOwnProperty("endPoint")) {
            for (var i = 0; i < system.content.composite.endPoint.length; i++) {
                var endPoint = system.content.composite.endPoint[i];
                endPoint.parent = system;
                this.initPoint(endPoint, ENDPOINT);
            }
        }
        if (system.content.composite.hasOwnProperty("exitPoint")) {
            for (var i = 0; i < system.content.composite.exitPoint.length; i++) {
                var exitPoint = system.content.composite.exitPoint[i];
                exitPoint.parent = system;
                this.initPoint(exitPoint, EXITPOINT);
            }
        }
        if (system.content.composite.hasOwnProperty("preCondition")) {
            for (var i = 0; i < system.content.composite.preCondition.length; i++) {
                var preCondition = system.content.composite.preCondition[i];
                preCondition.parent = system;
                this.initPoint(preCondition, PRECOND);
            }
        }
        if (system.content.composite.hasOwnProperty("postCondition")) {
            for (var i = 0; i < system.content.composite.postCondition.length; i++) {
                var postCondition = system.content.composite.postCondition[i];
                postCondition.parent = system;
                this.initPoint(postCondition, POSTCOND);
            }
        }
        if (system.content.composite.hasOwnProperty("subArray")) {
            for (var i = 0; i < system.content.composite.subArray.length; i++) {
                var array = system.content.composite.subArray[i];
                array.parent = system;
                this.initArray(array);
            }
        }

    }
};
_dss_editor._model.system.initArray = function(array) {
    array.style = ARRAY;
    //this.initBasicMethod(array);
    array.getChildren = function() {
        return this.subInstance;
    };
    array.getInstances = array.getChildren;
    array.addInstance = function(instance) {
        instance.parent = this;
        this.subInstance.push(instance);
        this.updateInstance();
    };
    array.removeInstance = function(instance) {
        _dss_editor._toolkit.removeArrayElement(this.subInstance, instance);
        this.updateInstance();
    };
    array.removeChild = array.removeInstance;
    array.updateInstance = function() {
        for (var i = 0; i < this.subInstance.length; i++) {
            var ins = array.subInstance[i];
            ins.index = i + 1;
            var noVisibleCnt = 0;
            for (var j = i + 1; j < this.subInstance.length; j++) {
                var nextIns = array.subInstance[j];
                if (!nextIns.isVisible()) {
                    noVisibleCnt++;
                }
            }
            if (noVisibleCnt > 0) {
                ins.setHasShadow(YES);
            } else {
                ins.setHasShadow(NO);
            }
            if (i == 0) {
                ins.setVisible(YES);
            }
            ins.setStaticCnt(noVisibleCnt + 1);
        }
    };
    array.getLogicFullName = function() {
        if (!this.hasOwnProperty('fullName')) {
            return this.getFullName();
        }
        return this.fullName;
    };
    // 这个是物理上的全名，与当前显示的关系保持一致
    array.getFullName = function() {
        // if(!this.hasOwnProperty('fullName')){
        this.completeName = this.name;
        var d = this;
        while (d.hasOwnProperty('parent') && d.parent.hasOwnProperty('parent')) {
            d = d.parent;
            if (d.style == ARRAY) {
                continue;
            }
            this.completeName = d.name + '.' + this.completeName;
        }
        // }
        return this.completeName;
    };
    for (var i in array.subInstance) {
        var instance = array.subInstance[i];
        this.initSystem(instance);
        instance.parent = array;
        instance.index = parseInt(i) + 1;
        if (i == 0) {
            instance.showInfo.visible = YES;
        } else {
            instance.showInfo.visible = NO;
        }
    }
};
_dss_editor._model.system.initPoint = function(point, type) {
    point.handles = [];
    point.textHandles = [];
    point.type = type;
    point.style = POINT;

    if (!point.hasOwnProperty('showInfo')) {
        point.showInfo = {};
    }
    if (type == EXITPOINT || type == PRECOND || type == POSTCOND) {
        point.showInfo.w = EXITPOINTW;
        point.showInfo.h = EXITPOINTH;
        if (point.hasOwnProperty('parent')) {
            var dir = _dss_editor._toolkit.calculatePointDir(point.showInfo, point.parent);
            point.showInfo.angle = _dss_editor._model.link.genAngle(point.parent, point.showInfo);
        }
    } else {
        point.showInfo.w = POINTLENGTH;
        point.showInfo.h = POINTLENGTH;
    }
    this.initSystemMethod(point);

};
_dss_editor._model.system.initBasicMethod = function(system) {
    system.getName = function() {
        if (!this.hasOwnProperty('name')) {
            this.name = '';
        }
        return this.name;
    };

    system.setName = function(name) {
        this.name = name;
        this.updateLinks();
    };
    // 这个是物理上的全名，与当前显示的关系保持一致
    system.getFullName = function() {
        // if(!this.hasOwnProperty('fullName')){
        this.completeName = this.getName();
        var d = this;
        while (d.hasOwnProperty('parent') && d.parent.hasOwnProperty('parent')) {
            d = d.parent;
            if (d.style == ARRAY) {
                continue;
            }
            this.completeName = d.name + '.' + this.completeName;
        }
        // }
        return this.completeName;
    };

    // 得到的是逻辑上的全名，针对UIO 中不会显示完整图而言。
    system.getLogicFullName = function() {
        if (!this.hasOwnProperty('fullName')) {
            return this.getFullName();
        }
        return this.fullName;
    };
    system.getParent = function() {
        if (!this.hasOwnProperty('parent')) {
            this.parent = null;
        }
        return this.parent;
    };
    system.addHandle = function(handle) {
        if ( handle instanceof EditTool) {
            this.textHandles.push(handle);
        } else if ( handle instanceof HandleTool) {
            this.handles.push(handle);
        }
    };
    system.removeHandle = function(handle) {
         if ( handle instanceof EditTool) {
            this.textHandles.splice($.inArray(this.textHandles,handle),1);
        } 
       
    };
    system.clearHandles = function() {
        for (var i in this.textHandles) {
            if (this.textHandles[i] instanceof EditTool) {
                this.textHandles[i].close();
            }
        }
        this.textHandles = [];
        this.handles = [];
    };
};
_dss_editor._model.system.initProtocolMethod = function(system) {
    system.setFrom = function(from) {
        if (!this.hasOwnProperty('specSys')) {
            this.specSys = {};
        }
        if (!this.specSys.hasOwnProperty('protocol')) {
            this.specSys.protocol = {};
        }
        this.specSys.protocol.from = from;
    };
    system.getTo = function() {
        if (this.hasOwnProperty('specSys') && this.specSys.hasOwnProperty('protocol') && this.specSys.protocol.hasOwnProperty('to')) {
            return this.specSys.protocol.to;
        }
        return '';
    };
    system.setTo = function(to) {
        if (!this.hasOwnProperty('specSys')) {
            this.specSys = {};
        }
        if (!this.specSys.hasOwnProperty('protocol')) {
            this.specSys.protocol = {};
        }
        this.specSys.protocol.to = to;
    };
};
_dss_editor._model.system.initWorkMethod = function(system) {
    var that = this;
    system.getDeriveFlag = function() {
        if (this.hasOwnProperty('specSys') && this.specSys.hasOwnProperty('work') && this.specSys.work.hasOwnProperty('deriveInfo') && this.specSys.work.deriveInfo.hasOwnProperty('deriveFlag')) {
            return getValue(this.specSys.work.deriveInfo.deriveFlag);
        }
        return NOTDERIVE;
    };

    system.setDeriveFlag = function(deriveFlag) {
        if (this.getType() != that._type.WORK && this.userDefinedType != that._type.WORK) {
            return;
        }
        if (!this.hasOwnProperty('specSys')) {
            this.specSys = {};
        }
        if (!this.specSys.hasOwnProperty('work')) {
            this.specSys.work = {};
        }
        if (!this.specSys.work.hasOwnProperty('deriveInfo')) {
            this.specSys.work.deriveInfo = {};
        }
        this.specSys.work.deriveInfo.deriveFlag = NOTDERIVE + "," + SENDER + "," + RECEIVER + ";" + deriveFlag;
    };

    system.getDeriveProtoName = function() {
        if (this.hasOwnProperty('specSys') && this.specSys.hasOwnProperty('work') && this.specSys.work.hasOwnProperty('deriveInfo') && this.specSys.work.deriveInfo.hasOwnProperty('deriveProtoName')) {
            return this.specSys.work.deriveInfo.deriveProtoName;
        }
        return '';
    };

    system.setDeriveProtoName = function(deriveProtoName) {
        if (this.hasOwnProperty('specSys') && this.specSys.hasOwnProperty('work') && this.specSys.work.hasOwnProperty('deriveInfo') && this.specSys.work.deriveInfo.hasOwnProperty('deriveProtoName')) {
            this.specSys.work.deriveInfo.deriveProtoName = deriveProtoName;
        }
        return '';
    };

    system.getPartiProtoName = function() {
        if (this.hasOwnProperty('specSys') && this.specSys.hasOwnProperty('work') && this.specSys.work.hasOwnProperty('deriveInfo') && this.specSys.work.deriveInfo.hasOwnProperty('partiProtoName')) {
            return this.specSys.work.deriveInfo.partiProtoName;
        }
        return '';
    };

    system.setPartiProtoName = function(partiProtoName) {
        if (this.hasOwnProperty('specSys') && this.specSys.hasOwnProperty('work') && this.specSys.work.hasOwnProperty('deriveInfo') && this.specSys.work.deriveInfo.hasOwnProperty('partiProtoName')) {
            this.specSys.work.deriveInfo.partiProtoName = partiProtoName;
        }
        return '';
    };
};
_dss_editor._model.system.initSystemMethod = function(system) {
    var that = this;
    that.initBasicMethod(system);
    system.getRectangle = function() {
        var rectangle = null;
        if (this.hasOwnProperty('showInfo')) {
            if (this.style == POINT) {
                rectangle = {};
                if (this.type == EXITPOINT) {
                    var loc = getAnchorPoint(this.parent, this.showInfo.angle);
                    rectangle = _dss_editor._toolkit.calculatePointBounds(loc, this.parent);
                } else {
                    rectangle.x = this.showInfo.x;
                    rectangle.y = this.showInfo.y;
                    rectangle.h = this.showInfo.h;
                    rectangle.w = this.showInfo.w;
                }
            } else if (this.style == SYSTEM) {
                if (this.showInfo.hasOwnProperty('rectangle')) {
                    rectangle = {};
                    this.showInfo.rectangle.h = this.showInfo.rectangle.h > that.minSize.height ? this.showInfo.rectangle.h : that.minSize.height;
                    this.showInfo.rectangle.w = this.showInfo.rectangle.w > that.minSize.width ? this.showInfo.rectangle.w : that.minSize.width;
                    rectangle.x = this.showInfo.rectangle.x;
                    rectangle.y = this.showInfo.rectangle.y;
                    rectangle.h = this.showInfo.rectangle.h;
                    rectangle.w = this.showInfo.rectangle.w;
                    //如果隐藏了内容，则在取大小的时候需要重新计算！
                    if (getValue(this.showInfo.showContent) == NO) {
                        var fitw = _dss_editor._toolkit.measureText(this.name);
                        rectangle.h = 30;
                        rectangle.w = this.showInfo.rectangle.w;
                        rectangle.w = rectangle.w > _dss_editor._model.system.minSize.width ? rectangle.w : _dss_editor._model.system.minSize.width;
                        rectangle.w = rectangle.w > fitw ? rectangle.w : fitw;
                    }
                }
            }
        }
        return rectangle;
    };

    system.setRectangle = function(rectangle) {
        if (this.style == POINT) {
            this.showInfo = rectangle;
        } else if (this.style == SYSTEM) {
            if (this.showInfo.hasOwnProperty('rectangle')) {
                if (getValue(this.showInfo.showContent) == NO) {
                    rectangle.h = this.showInfo.rectangle.h;
                }
                this.showInfo.rectangle = rectangle;
            }
        }
    };

    system.getFrom = function() {
        if (this.getType() == that._type.PROTOCOL) {
            if (this.hasOwnProperty('specSys') && this.specSys.hasOwnProperty('protocol')
            // &&                                                                            this.specSys.protocol.hasOwnProperty('simple')
            && this.specSys.protocol.hasOwnProperty('from')) {
                return this.specSys.protocol.from;
            }
        }
        return '';
    };
    system.isShowLabel = function() {
        if (this.getType() == COMMENT) {
            return false;
        }
        if (this.hasOwnProperty('showInfo') && this.showInfo.hasOwnProperty('showLabel')) {
            var showLabel = getValue(this.showInfo.showLabel);
            if (showLabel == YES) {
                return true;
            }
        }
        return false;
    };

    system.setShowLabel = function(showLabel) {
        if (this.hasOwnProperty('showInfo') && this.showInfo.hasOwnProperty('showLabel')) {
            this.showInfo.showLabel = YES + "," + NO + ";" + showLabel;
        }
    };

    system.isShowContent = function() {
        if (this.hasOwnProperty('showInfo') && this.showInfo.hasOwnProperty('showContent')) {
            var showContent = getValue(this.showInfo.showContent);
            if (showContent == YES) {
                return true;
            }
        }
        return false;
    };

    system.setShowContent = function(showContent) {
        if (!this.hasOwnProperty('showInfo')) {
            //				this.showInfo = {};
            return;
        }
        if (!this.showInfo.hasOwnProperty('showContent')) {
            //				this.showInfo.showContent = '';
            return;
        }

        if (showContent == true || showContent == YES) {
            this.showInfo.showContent = YES + "," + NO + ";" + YES;
        } else {
            this.showInfo.showLabel = YES + "," + NO + ";" + YES;
            this.showInfo.showContent = YES + "," + NO + ";" + NO;
        }
    };

    system.isVisible = function() {
        if (this.hasOwnProperty('showInfo') && this.showInfo.hasOwnProperty('visible')) {
            var visible = getValue(this.showInfo.visible);
            if (visible == NO) {
                return false;
            }
        }
        return true;
    };

    system.setVisible = function(visible) {
        if (this.hasOwnProperty('showInfo') && this.showInfo.hasOwnProperty('visible')) {
            this.showInfo.visible = YES + "," + NO + ";" + visible;
        }
    };

    system.getChildren = function() {
        var children = [];
        if (this.hasOwnProperty('content') && this.content.hasOwnProperty('composite')) {
            if (this.content.composite.hasOwnProperty("subSys")) {
                children = children.concat(this.content.composite.subSys);
            }
            if (this.content.composite.hasOwnProperty("subArray")) {
                children = children.concat(this.content.composite.subArray);
            }
            if (this.content.composite.hasOwnProperty("beginPoint")) {
                children = children.concat(this.content.composite.beginPoint);
            }
            if (this.content.composite.hasOwnProperty("endPoint")) {
                children = children.concat(this.content.composite.endPoint);
            }
            if (this.content.composite.hasOwnProperty("exitPoint")) {
                children = children.concat(this.content.composite.exitPoint);
            }
            if (this.content.composite.hasOwnProperty("preCondition")) {
                children = children.concat(this.content.composite.preCondition);
            }
            if (this.content.composite.hasOwnProperty("postCondition")) {
                children = children.concat(this.content.composite.postCondition);
            }
        }
        return children;
    };

    system.getChildByName = function(name) {
        var children = this.getChildren();
        for (var i = 0; i < children.length; i++) {
            var child = children[i];
            if (child.getName() == name) {
                return child;
            };
        }
        return null;
    };

    system.addChild = function(child) {
        if (!this.hasOwnProperty("content")) {
            this.content = {};
        }
        if (this.content.hasOwnProperty(SIMPLE)) {
            delete this.content.simple;
        }
        if (!this.content.hasOwnProperty("composite")) {
            this.content.composite = {};
        }
        // if (System.isArrayInstance(child)) {
        // child = child.parent;
        // }
        if (child.parent != null) {
            child.parent.removeChild(child);
        }
        child.parent = this;
        if (child.style == SYSTEM) {
            if (!this.content.composite.hasOwnProperty('subSys')) {
                this.content.composite.subSys = [];
            }
            this.content.composite.subSys.push(child);
        } else if (child.type == BEGINPOINT) {
            if (!this.content.composite.hasOwnProperty('beginPoint')) {
                this.content.composite.beginPoint = [];
            }
            this.content.composite.beginPoint.push(child);
        } else if (child.type == ENDPOINT) {
            if (!this.content.composite.hasOwnProperty('endPoint')) {
                this.content.composite.endPoint = [];
            }
            this.content.composite.endPoint.push(child);
        } else if (child.type == EXITPOINT) {
            if (!this.content.composite.hasOwnProperty('exitPoint')) {
                this.content.composite.exitPoint = [];
            }
            this.content.composite.exitPoint.push(child);
        } else if (child.type == PRECOND) {
            if (!this.content.composite.hasOwnProperty('preCondition')) {
                this.content.composite.preCondition = [];
            }
            this.content.composite.preCondition.push(child);
        } else if (child.type == POSTCOND) {
            if (!this.content.composite.hasOwnProperty('postCondition')) {
                this.content.composite.postCondition = [];
            }
            this.content.composite.postCondition.push(child);
        } else if (child.style == ARRAY) {
            if (!this.content.composite.hasOwnProperty('subArray')) {
                this.content.composite.subArray = [];
            }
            this.content.composite.subArray.push(child);
        }
        ;

    };

    system.removeChild = function(child) {
        if (this.hasOwnProperty("content")) {
            // var content = this.content;
            if (this.content.hasOwnProperty('composite')) {
                if (child.style == SYSTEM) {
                    _dss_editor._toolkit.removeArrayElement(this.content.composite.subSys, child);
                } else if (child.style == ARRAY) {
                    _dss_editor._toolkit.removeArrayElement(this.content.composite.subArray, child);
                } else if (child.type == BEGINPOINT) {
                    _dss_editor._toolkit.removeArrayElement(this.content.composite.beginPoint, child);
                } else if (child.type == ENDPOINT) {
                    _dss_editor._toolkit.removeArrayElement(this.content.composite.endPoint, child);
                } else if (child.type == EXITPOINT) {
                    _dss_editor._toolkit.removeArrayElement(this.content.composite.exitPoint, child);
                } else if (child.type == PRECOND) {
                    _dss_editor._toolkit.removeArrayElement(this.content.composite.preCondition, child);
                } else if (child.type == POSTCOND) {
                    _dss_editor._toolkit.removeArrayElement(this.content.composite.postCondition, child);
                }
            }
            ;
        }
        ;
    };

    system.getBeginPoints = function() {
        if (this.hasOwnProperty('content') && this.content.hasOwnProperty('composite') && this.content.composite.hasOwnProperty("beginPoint")) {
            return this.content.composite.beginPoint;
        }
        return null;
    };

    system.getEndPoints = function() {
        if (this.hasOwnProperty('content') && this.content.hasOwnProperty('composite') && this.content.composite.hasOwnProperty("beginPoint")) {
            return this.content.composite.beginPoint;
        }
        return null;
    };

    // 简单system的content
    system.getContent = function() {
        if (this.hasOwnProperty('content') && this.content.hasOwnProperty('simple')) {
            return this.content.simple;
        }
        return null;
    };
    //simple
    system.setContent = function(content) {
        if (!this.hasOwnProperty('content')) {
            this.content = {};
        }
        if (!this.content.hasOwnProperty('simple')) {
            this.content.simple = '';
        }
        this.content.simple = content;
    };
    // content的结构包含了类型以及初始值，这个方法得到的只是初始值
    system.getValue = function() {
        if (this.hasOwnProperty('content') && this.content.hasOwnProperty('simple') && this.content.simple.hasOwnProperty('expr')) {
            if (this.getType() == COMMENT) {
                return this.content.simple.expr;
            }
            return getValue(this.content.simple.expr);
        }
        return '';
    };

    system.setValue = function(value) {
        var content = '';
        if (!this.hasOwnProperty('content')) {
            this.content = {};
        }
        if (!this.content.hasOwnProperty('simple') || typeof (this.content.simple) == 'string') {
            content = this.content.simple;
            this.content.simple = {};
        }
        if (!this.content.simple.hasOwnProperty('expr')) {
            this.content.simple.expr = '';
        } else {
            content = this.content.simple.expr;
        }

        var i = content.lastIndexOf(";") + 1;
        if (content.charAt(0) == "\"") {
            this.content.simple.expr = value;
        } else {
            this.content.simple.expr = value;
            //this.content.simple.expr = content.substring(0, i) + value;
        }
    };

    system.hasShadow = function() {
        this.property = this.property || {};
        this.property.hasShadow = this.property.hasShadow || NO;
        var hasShadow = getValue(this.property.hasShadow);
        if (hasShadow == YES) {
            return true;
        }
        return false;
    };

    system.setHasShadow = function(hasShadow) {
        this.property = this.property || {};
        //this.property.hasShadow = this.property.hasShadow || hasShadow;
        if (hasShadow == true) {
            hasShadow = YES;
        } else if (hasShadow == false) {
            hasShadow = NO;
        }
        // if (hasShadow == YES && !ArrayTool.isArrayInstance(this)) {
        // system.name += '[*]';
        // } else if (hasShadow == NO && this.hasShadow()) {
        // system.name = _dss_editor._toolkit.strReplaceAll(system.name, '[*]', '');
        // }

        this.property.hasShadow = YES + "," + NO + ";" + hasShadow;

    };

    system.getStaticCnt = function() {
        if (this.hasOwnProperty('property') && this.property.hasOwnProperty('staticCnt')) {
            return this.property.staticCnt;
        }
        return '';
    };

    system.setStaticCnt = function(staticCnt) {
        if (!this.hasOwnProperty('property')) {
            this.property = {};
        }
        this.property.staticCnt = staticCnt;
        // if (this.hasOwnProperty('property') && this.property.hasOwnProperty('staticCnt')) {
        //
        // }
    };

    system.getVersion = function() {
        if (this.hasOwnProperty('property') && this.property.hasOwnProperty('version')) {
            return this.property.version;
        }
        return 0;
    };

    system.setVersion = function(version) {
        if (this.hasOwnProperty('property') && this.property.hasOwnProperty('version')) {
            this.property.version = version;
        }
    };

    system.isInstantiate = function() {
        if (this.hasOwnProperty('property') && this.property.hasOwnProperty('instantiate')) {
            var instantiate = getValue(this.property.instantiate);
            if (instantiate == YES) {
                return true;
            }
        }
        return false;
    };

    system.setInstantiate = function(instantiate) {
        if (!this.hasOwnProperty('property')) {
            this.property = {};
        }
        this.property.instantiate = YES + "," + NO + ";" + instantiate;
    };

    system.getType = function() {
        if (this.hasOwnProperty('type')) {
            var type = this.type;
            type = getValue(type);
            return type;
        }
        return null;
    };

    system.setType = function(type) {
        if (this.hasOwnProperty('type')) {
            this.type = "System,Work,Data,Predicate,Protocol;" + type;
        }
    };

    system.getSystemComplexity = function() {
        if (this.hasOwnProperty('content') && this.content.hasOwnProperty("composite")) {
            return 2;
        } else {
            return 1;
        }
    };

    system.getLinkFrom = function() {
        if (this.hasOwnProperty('linkFrom')) {
            return this.linkFrom;
        } else if (this.hasOwnProperty('transFrom')) {
            return this.transFrom;
        }
    };

    system.addLinkFrom = function(link) {
        if (!this.getLinkFrom()) {
            this.linkFrom = [];
        }
        this.getLinkFrom().push(link);
        link.setFromSystem(this);
    };

    system.removeLinkFrom = function(link) {
        _dss_editor._toolkit.removeArrayElement(this.getLinkFrom(), link);
    };

    system.getLinkTo = function() {
        if (this.hasOwnProperty('linkTo')) {
            return this.linkTo;
        } else if (this.hasOwnProperty('transTo')) {
            return this.transTo;
        }
    };

    system.addLinkTo = function(link) {
        if (!this.getLinkTo()) {
            this.linkTo = [];
        }
        this.getLinkTo().push(link);
        link.setToSystem(this);
    };

    system.removeLinkTo = function(link) {
        _dss_editor._toolkit.removeArrayElement(this.getLinkTo(), link);
    };

    system.updateLinks = function() {
        //var links = _dss_editor._toolkit.getSystemAllInnerLinks(this);

        for (var i in this.getLinkFrom()) {
            var link = this.getLinkFrom()[i];
            link.updateFrom();
        }
        for (var i in this.getLinkTo()) {
            var link = this.getLinkTo()[i];
            link.updateTo();
        }
        for (var i in this.getChildren()) {
            var sub = this.getChildren()[i];
            sub.updateLinks();
        }
    };

};
_dss_editor._model.system.getLabelText = function(system) {
    var text = system.getName();
    if (system.index != undefined) {
        text += '[' + system.index + ']';
    } else if (system.hasShadow()) {
        text += '[*]';
    }
    return text;
};
_dss_editor._model.system.getAllSubs = function(system) {
    var allSubs = system.getChildren();
    for (var i = 0; i < system.getChildren().length; i++) {
        var sub = system.getChildren()[i];
        allSubs = allSubs.concat(this.getAllSubs(sub));
    };
    return allSubs;
};
// 新的JSON接口里，使用 type;value的格式，所以要得到value需要解析
function getValue(content) {
    if (!content) {
        return content;
    }
    var i = content.lastIndexOf(";") + 1;
    if (content.charAt(0) == "\"") {
        return content;
    } else {
        var value = _dss_editor._toolkit.trimStr(content.substring(i, content.length));
        return value;
    }
    ;
}

// 模型相关
// create
//_dss_editor._model.system.factory = {
_dss_editor._model.system.create = function(t) {
    if (t.style == SYSTEM) {
        return this.createSystemByType(t);
    } else if (t.style == POINT) {
        return this.createPoint(t.type);
    }
};

_dss_editor._model.system.createPoint = function(type) {
    var point = {
        name : '',
        showInfo : {
            x : 0,
            y : 0
        },
        linkFrom : [],
        linkTo : []
    };
    var date = new Date();
    point.name = 'P' + date.getUTCFullYear() + date.getUTCMonth() + date.getUTCDate() + date.getHours() + date.getUTCMinutes() + date.getUTCSeconds();
    _dss_editor._model.system.initPoint(point, type);
    return point;
};

_dss_editor._model.system.createSystemByType = function(t) {
    var system = this.createBasicSystem();
    _dss_editor._model.system.initSystem(system);
    var changeTypeCmd = new ChangeTypeCommand();
    changeTypeCmd.system = system;
    changeTypeCmd.type = t;
    changeTypeCmd.execute();
    return system;
};

// 创建一个没有类型的基本的图元
_dss_editor._model.system.createBasicSystem = function() {
    var system = {
        type : '', // "System,Work,Data,Predicate,Protocol;" + t,
        name : 'new',
        superSys : {},
        showInfo : {
            rectangle : {
                x : 0,
                y : 0,
                w : 120,
                h : 60
            },
            color : "black",
            visible : YES + "," + NO + ";" + YES,
            showContent : YES + "," + NO + ";" + YES,
            showLabel : YES + "," + NO + ";" + YES
        },
        content : {
            simple : {
                expr : ''
            }
        },
        property : {
            hasShadow : YES + "," + NO + ";" + NO,
            instantiate : YES + "," + NO + ";" + NO,
            staticCnt : "",
            version : 0
        },
        specSys : {},
        linkFrom : [],
        linkTo : []
    };
    return system;
};
//};
